package com.hefan.live.listener;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.cat.tiger.util.GlobalConstants;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hefan.common.ons.TopicRegistry;
import com.hefan.common.ons.TopicRegistryDev;
import com.hefan.common.ons.TopicRegistryTest;
import com.hefan.common.ons.listener.GLLMessageListener;
import com.hefan.common.util.MapUtils;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import com.hefan.user.itf.WebUserWatchDayService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户离开直播间经验值结算
 * 
 * @author kevin_zhang
 *
 */
@Component
public class LiveUserExperienceOptListener implements GLLMessageListener {
	Logger logger = LoggerFactory.getLogger(LiveUserExperienceOptListener.class);

	@Resource
	WebUserService webUserService;
	@Resource
	WebUserWatchDayService webUserWatchDayService;

	@Override
	public TopicRegistry getTopicRegistry() {
		return TopicRegistry.HEFAN_LIVE_USER_EXPERIENCE;
	}

	@Override
	public TopicRegistryDev getTopicRegistryDev() {
		return TopicRegistryDev.HEFAN_LIVE_USER_EXPERIENCE_DEV;
	}

	@Override
	public TopicRegistryTest getTopicRegistryTest() {
		return TopicRegistryTest.HEFAN_LIVE_USER_EXPERIENCE_TEST;
	}

	@SuppressWarnings({ "rawtypes" })
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	@Override
	public Action consume(Message arg0, ConsumeContext arg1) {
		String realTopic = arg0.getTag();
		logger.info("HEFAN_LIVE_USER_EXPERIENCE receiver MessageListener topic: {}, realTopic : {}, msg_body: {}",
				arg0.getTopic(), realTopic, new String(arg0.getBody()));
		try {
			Map paramMap = new ObjectMapper().readValue(arg0.getBody(), Map.class);
			if (null != paramMap && !paramMap.isEmpty()) {
				if (paramMap.containsKey("liveUserExperience")) {
					Map map = JSON.parseObject((String) paramMap.get("liveUserExperience"), Map.class);

					String userId = MapUtils.getStrValue(map, "userId", "");// 用户id
					long watchTime = MapUtils.getLongValue(map, "watchTime", 0);// 观看时长
					if (StringUtils.isBlank(userId) || watchTime <= 0) {
						logger.info("用户经验结算－－参数校验不通过");
						return Action.CommitMessage;
					}

					WebUser webUser = webUserService.getWebUserInfoByUserId(userId);
					if (webUser==null){
						logger.error("用户不存在");
						return Action.CommitMessage;
					}

					logger.info("用户经验结算－－开始");
					// 更新经验
					try {
						if (webUser.getUserType() != GlobalConstants.USER_TYPE_FAMOUS && webUser.getUserType()!=GlobalConstants.USER_TYPE_STAR
								&& webUser.getUserType()!=GlobalConstants.USER_TYPE_SITE) {
							webUserWatchDayService.updateUserExpByWatchTime(userId, watchTime);
						}
					}catch (Exception e){
						e.printStackTrace();
						logger.error("用户经验结算-失败");
					}
					logger.info("用户经验结算－－结束");

					// 更新时长
				/*	if (webUserService.updateUserWatchTime(userId, watchTime) >= 1) {
						return Action.CommitMessage;
					} else {
						throw new RuntimeException("用户更新时长失败");
					}*/
				} else {
					logger.info("用户经验结算－－无任何操作");
				}
			} else {
				logger.info("用户经验结算－－无参数");
			}
			return Action.CommitMessage;
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("用户经验结算－－用户经验结算失败：" + e.getMessage());
			return Action.ReconsumeLater;
		} finally {
			logger.info("HEFAN_LIVE_USER_EXPERIENCE receiver finish");
		}
	}
}
